<template>
  <div class="container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="工序编码">
          <el-input v-model="searchForm.operationCode" placeholder="请输入工序编码" clearable />
        </el-form-item>
        <el-form-item label="工序名称">
          <el-input v-model="searchForm.operationName" placeholder="请输入工序名称" clearable />
        </el-form-item>
        <el-form-item label="是否启用">
          <el-select v-model="searchForm.isYes" placeholder="是否启用" style="width: 100px;" clearable>
            <el-option label="是" value="1" />
            <el-option label="否" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 按钮工具栏 -->
    <div class="button-container">
      <el-button type="primary" class="custom-button add-button" @click="handleAdd">
        <el-icon><Plus /></el-icon>新增
      </el-button>
      <el-button type="danger" class="custom-button delete-button" @click="handleBatchDelete" :disabled="selectedRows.length === 0">
        <el-icon><Delete /></el-icon>删除
      </el-button>
      <el-button type="warning" class="custom-button export-button" @click="handleExport">
        <el-icon><Download /></el-icon>导出
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      @selection-change="handleSelectionChange"
      style="width: 100%"
      border
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column prop="operationCode" label="工序编码" min-width="120" show-overflow-tooltip />
      <el-table-column prop="operationName" label="工序名称" min-width="120" show-overflow-tooltip />
      <el-table-column prop="isYes" label="是否启用" min-width="80" align="center">
        <template #default="scope">
          <el-tag type="success" v-if="scope.row.isYes === '1'">是</el-tag>
          <el-tag type="info" v-else>否</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="speak" label="备注" min-width="180" show-overflow-tooltip />
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="scope">
          <el-button type="success" class="custom-button edit-button" @click="handleEdit(scope.row)">
            <el-icon><Edit /></el-icon>修改
          </el-button>
          <el-button type="danger" class="custom-button delete-button" @click="handleSingleDelete(scope.row)">
            <el-icon><Delete /></el-icon>删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
      />
    </div>

    <!-- 添加/修改工序对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '修改生产工序' : '添加生产工序'"
      width="600px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="100px"
        class="form"
      >
        <el-form-item label="工序编码" prop="operationCode">
          <div style="display: flex; align-items: center;">
            <el-input v-model="form.operationCode" placeholder="请输入工序编码" :disabled="form.autoGenerate" />
            <el-switch v-model="form.autoGenerate" style="margin-left: 10px;" active-text="自动生成" />
          </div>
        </el-form-item>
        
        <el-form-item label="工序名称" prop="operationName">
          <el-input v-model="form.operationName" placeholder="请输入工序名称" />
        </el-form-item>

        <el-form-item label="是否启用" prop="isYes">
          <el-radio-group v-model="form.isYes">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="工序说明" prop="operationSpeak">
          <el-input
            v-model="form.operationSpeak"
            type="textarea"
            :rows="3"
            placeholder="请输入内容"
          />
        </el-form-item>

        <el-form-item label="备注" prop="speak">
          <el-input
            v-model="form.speak"
            type="textarea"
            :rows="3"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import http from '@/api/http'
import { Plus, Edit, Delete, Download } from '@element-plus/icons-vue'

// 搜索表单数据
const searchForm = reactive({
  operationCode: '',
  operationName: '',
  isYes: ''
})

// 分页相关数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableData = ref([])
const loading = ref(false)

// 选中的行
const selectedRows = ref([])

// 对话框相关数据
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref(null)
const submitLoading = ref(false)

// 表单数据
const form = reactive({
  id: 0,
  operationCode: '',
  operationName: '',
  isYes: '0',
  operationSpeak: '',
  speak: '',
  autoGenerate: false
})

// 表单校验规则
const formRules = {
  operationCode: [{ required: true, message: '请输入工序编码', trigger: 'blur' }],
  operationName: [{ required: true, message: '请输入工序名称', trigger: 'blur' }],
  isYes: [{ required: true, message: '请选择是否启用', trigger: 'change' }]
}

// 生成工序编码
const generateProcessCode = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')
  return `OPEN${year}${month}${day}${hours}${minutes}${seconds}`
}

// 监听自动生成开关
watch(() => form.autoGenerate, (newVal) => {
  if (newVal) {
    form.operationCode = generateProcessCode()
  }
})

// 获取表格数据
const fetchData = async () => {
  loading.value = true
  try {
    const queryParams = {
      PageIndex: currentPage.value,
      PageSize: pageSize.value,
      SearchKeyword: ''
    }

    if (searchForm.operationCode) queryParams.OperationCode = searchForm.operationCode.trim()
    if (searchForm.operationName) queryParams.OperationName = searchForm.operationName.trim()
    if (searchForm.isYes) queryParams.IsYes = searchForm.isYes

    console.log('请求参数:', queryParams)

    const response = await http.get('/api/OperationModel/QueryOperationModelList', queryParams)
    console.log('API响应:', response)

    if (response?.data?.items && Array.isArray(response.data.items)) {
      tableData.value = response.data.items
      total.value = response.data.total || response.data.items.length || 0
    } else if (response?.data && Array.isArray(response.data)) {
      tableData.value = response.data
      total.value = response.data.length
    } else if (response?.result?.items && Array.isArray(response.result.items)) {
      tableData.value = response.result.items
      total.value = response.result.total || response.result.items.length
    } else {
      throw new Error('接口返回数据格式不正确')
    }

    if (tableData.value.length === 0) {
      ElMessage.info('暂无数据')
    }
  } catch (error) {
    console.error('获取数据错误:', error)
    ElMessage.error('获取数据失败：' + (error.message || '未知错误'))
    tableData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

// 重置
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  currentPage.value = 1
  pageSize.value = 10
  fetchData()
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchData()
}

// 页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

// 新增
const handleAdd = () => {
  isEdit.value = false
  dialogVisible.value = true
  form.autoGenerate = true
  form.isYes = '1'
  form.operationCode = generateProcessCode()
}

// 编辑
const handleEdit = (row) => {
  isEdit.value = true
  dialogVisible.value = true
  // 确保所有字段都有默认值，防止undefined
  form.id = row.id || row.Id || 0
  form.operationCode = row.operationCode || row.OperationCode || ''
  form.operationName = row.operationName || row.OperationName || ''
  // 确保isYes是字符串类型
  form.isYes = (row.isYes || row.IsYes || '0').toString()
  form.operationSpeak = row.operationSpeak || row.OperationSpeak || ''
  form.speak = row.speak || row.Speak || ''
  form.autoGenerate = false
  
  // 打印一下数据，方便调试
  console.log('编辑行数据:', row)
  console.log('表单数据:', form)
}

// 删除（支持单个和批量）
const handleDelete = async (ids) => {
  try {
    // 将id数组转换为逗号分隔的字符串
    const idString = Array.isArray(ids) ? ids.join(',') : ids.toString()
    
    console.log('删除参数:', idString)
    
    // 使用GET请求，参数通过查询字符串传递
    const res = await http.get(`/api/OperationModel/BatchDeleteOperationModel?ids=${idString}`)
    
    // 兼容多种返回格式
    if (res?.status === true || res?.Status === true || res?.success === true || res?.Success === true) {
      ElMessage.success('删除成功')
      // 重置选中行
      selectedRows.value = []
      // 刷新数据
      fetchData()
    } else {
      throw new Error(res?.message || res?.Message || '删除失败')
    }
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败: ' + (error.message || '未知错误'))
  }
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }
  
  // 获取选中行的id数组
  const ids = selectedRows.value.map(row => row.id || row.Id || row.ID)
  
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedRows.value.length} 条记录吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      handleDelete(ids)
    })
    .catch(() => {
      // 取消删除
    })
}

// 单个删除
const handleSingleDelete = (row) => {
  if (!row || (!row.id && !row.Id && !row.ID)) {
    ElMessage.error('无效的记录ID')
    return
  }

  ElMessageBox.confirm(
    '确定要删除这条记录吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      handleDelete(row.id || row.Id || row.ID)
    })
    .catch(() => {
      // 取消删除
    })
}

// 导出
const handleExport = async () => {
  try {
    const params = {}
    if (searchForm.operationCode) params.OperationCode = searchForm.operationCode.trim()
    if (searchForm.operationName) params.OperationName = searchForm.operationName.trim()
    if (searchForm.isYes) params.IsYes = searchForm.isYes
    
    ElMessage.info('正在导出数据，请稍候...')
    await http.download('/api/OperationModel/ExportOperationModel', params, '生产工序数据.xlsx', true, () => {
      ElMessage.success('导出成功')
    })
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败: ' + (error.message || '未知错误'))
  }
}

// 对话框关闭时重置表单
const handleDialogClose = () => {
  formRef.value?.resetFields()
  Object.keys(form).forEach(key => {
    if (key === 'id') {
      form[key] = 0
    } else if (key === 'isYes') {
      form[key] = '0'
    } else if (key === 'autoGenerate') {
      form[key] = false
    } else {
      form[key] = ''
    }
  })
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        // 构造提交的数据
        const submitData = {
          id: form.id,
          operationCode: form.operationCode,
          operationName: form.operationName,
          isYes: form.isYes.toString(),
          operationSpeak: form.operationSpeak || '',
          speak: form.speak || ''
        }
        
        console.log('提交的数据:', submitData)
        
        const url = isEdit.value 
          ? '/api/OperationModel/BatchUpdateOperationModel'
          : '/api/OperationModel/AddOperationModel'
        
        // 如果是编辑，需要将数据包装成数组
        const requestData = isEdit.value ? [submitData] : submitData
        
        const response = await http.post(url, requestData)
        
        if (response?.status === true || response?.Status === true) {
          ElMessage.success(isEdit.value ? '修改成功' : '添加成功')
          dialogVisible.value = false
          fetchData()
        } else {
          throw new Error(response?.message || response?.Message || (isEdit.value ? '修改失败' : '添加失败'))
        }
      } catch (error) {
        console.error(isEdit.value ? '修改失败:' : '添加失败:', error)
        ElMessage.error((isEdit.value ? '修改' : '添加') + '失败: ' + (error.message || '未知错误'))
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 组件挂载时获取数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.container {
  padding: 20px;
}

.search-container {
  margin-bottom: 20px;
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.button-container {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.custom-button {
  border-radius: 4px;
  padding: 8px 15px;
  display: inline-flex;
  align-items: center;
  gap: 5px;
  font-size: 14px;
  border: none;
}

.custom-button .el-icon {
  margin-right: 4px;
}

.add-button {
  background-color: #ecf5ff;
  color: #409EFF;
}

.add-button:hover {
  background-color: #409EFF;
  color: #fff;
}

.edit-button {
  background-color: #f0f9eb;
  color: #67C23A;
}

.edit-button:hover {
  background-color: #67C23A;
  color: #fff;
}

.delete-button {
  background-color: #fef0f0;
  color: #F56C6C;
}

.delete-button:hover {
  background-color: #F56C6C;
  color: #fff;
}

.export-button {
  background-color: #fdf6ec;
  color: #E6A23C;
}

.export-button:hover {
  background-color: #E6A23C;
  color: #fff;
}

/* 禁用状态的按钮样式 */
.custom-button[disabled] {
  background-color: #f5f7fa !important;
  color: #c0c4cc !important;
  cursor: not-allowed;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.form {
  padding: 20px;
}

.dialog-footer {
  padding: 20px 0 0;
  text-align: right;
}

:deep(.el-form-item__label) {
  font-weight: bold;
}
</style>